package com.zdj.data.net;

import android.content.Context;

import java.io.File;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.OkHttpClient;

public class OkHttp3Utils {

    public static final String TAG = "OkHttp3Utils";

    private static OkHttpClient mOkHttpClient;

    //设置缓存目录
    private static File cacheDirectory ;
    private static Cache cache ;


    /**
     * 获取OkHttpClient对象
     *
     * @return
     */
    public static OkHttpClient getOkHttpClient(Context context) {

        if(context == null){
            throw new RuntimeException("must init NetWorks first before use it!!!");
        }

        // 配置缓存
        cacheDirectory = new File(context.getCacheDir().getAbsolutePath(), "MyCache");
        cache = new Cache(cacheDirectory, 10 * 1024 * 1024);

        if (null == mOkHttpClient) {
            mOkHttpClient = new OkHttpClient.Builder()
                    .addInterceptor(new LogInterceptor())
                    .addInterceptor(new HeaderInteceptor())
                    .addInterceptor(new CacheInterceptor(context))
                    //设置请求读写的超时时间
                    .connectTimeout(10, TimeUnit.SECONDS)
                    .writeTimeout(30, TimeUnit.SECONDS)
                    .readTimeout(30, TimeUnit.SECONDS)
                    .cache(cache)
                    .build();
        }
        return mOkHttpClient;
    }
}